import Koa from 'koa';
import bodyParser from '@koa/bodyparser';
import cors from '@koa/cors';
import helmet from 'koa-helmet';
import compress from 'koa-compress';
import json from 'koa-json';
import logger from 'koa-logger';
import serve from 'koa-static';
import Router from 'koa-router';
import dotenv from 'dotenv';
import path from 'path';

// 加载环境变量
dotenv.config();

// 导入路由
import characterRoutes from './routes/character';
import userRoutes from './routes/user';
import chatRoutes from './routes/chat';
import healthRoutes from './routes/health';

// 导入中间件
import { errorHandler } from './middleware/errorHandler';
import { notFoundHandler } from './middleware/notFoundHandler';

// 导入工具
import { logger as winstonLogger } from './utils/logger';
import { ErrorUtil } from './utils/errors';
import { ResponseUtil } from './utils/response';

// 创建Koa应用实例
const app: Koa = new Koa();

// 基础中间件配置
/* 
自动添加各种 HTTP 安全     
  头，保护应用免受常见攻击：       
  - X-Content-Type-Options:        
  nosniff - 防止 MIME 类型嗅探     
  - X-Frame-Options: DENY -        
  防止点击劫持
  - X-XSS-Protection: 1;
  mode=block - 启用 XSS 保护       
  - 等等...
*/
app.use(helmet()); // 安全头设置
app.use(compress()); // 响应压缩
/* 
CORS 跨域配置
*/
app.use(cors({
  origin: process.env.CORS_ORIGIN || '*', // 允许哪些域名访问（从环境变量读取，默认允许所有     ）
  credentials: true,
  allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowHeaders: ['Content-Type', 'Authorization'] // 允许的请求头
}));

// 请求解析中间件
app.use(bodyParser({
  jsonLimit: '10mb', // 解析JSON格式的请求体，当客户端发送Content-Type: application/json时，自动转换为JavaScript对象
  formLimit: '10mb', // 解析URL编码的表单数据
  textLimit: '10mb',
  encoding: 'utf-8'
}));

// JSON美化输出
app.use(json());

// 日志中间件
if (process.env.NODE_ENV !== 'test') {
  app.use(logger((str: string) => {
    winstonLogger.info(str.trim());
  }));
}

// 静态文件服务
app.use(serve(path.join(__dirname, '../public')));

// 创建API路由
const apiRouter = new Router();

// API根路径
apiRouter.get('/', async (ctx) => {
  ctx.body = ResponseUtil.success(ctx, {
    message: 'Dimensional Echo API',
    version: '1.0.0',
    endpoints: {
      characters: '/api/characters',
      users: '/api/users',
      chat: '/api/chat',
      health: '/health'
    }
  }, 'API信息');
});

// 注册API路由
apiRouter.use('/characters', characterRoutes.routes(), characterRoutes.allowedMethods());
apiRouter.use('/users', userRoutes.routes(), userRoutes.allowedMethods());
apiRouter.use('/chat', chatRoutes.routes(), chatRoutes.allowedMethods());

// 应用路由
app.use(apiRouter.routes());
app.use(apiRouter.allowedMethods());
app.use(healthRoutes.routes());
app.use(healthRoutes.allowedMethods());

// 错误处理中间件 (顺序很重要)
app.use(errorHandler);
app.use(notFoundHandler);

export default app;